﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;

namespace Experimental8
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
       
                protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
#if (DEBUG)
            RunInReleaseMode();// RunInDebugMode();
#else
           RunInReleaseMode();
#endif
            this.ShutdownMode = ShutdownMode.OnMainWindowClose;
        }

        private  void RunInDebugMode()
        {
            Experimental8Bootstrapper bootstrapper = new Experimental8Bootstrapper();
            bootstrapper.Run();
        }

        private void RunInReleaseMode()
        {
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;            
            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException; 
            
            try
            {
                Experimental8Bootstrapper bootstrapper = new Experimental8Bootstrapper();
                bootstrapper.Run();
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            HandleException(e.Exception as Exception);
        }

        private void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private static void HandleException(Exception ex)
        {            
            if (ex == null)
                return;

            ExceptionPolicy.HandleException(ex, "Unhandled Policy");
            MessageBox.Show(Experimental8.Properties.Resources.UnhandledException);
            Environment.Exit(1);
        }
    }
}
